const express = require('express');
const router = express.Router();
const { pool: db } = require('../../config/db'); // 确保你有数据库配置文件
const { generateUploadToken } = require('../../config/qiniu');


async function getVideosByPlatform(platform, page = 1, limit = 10) {
    const offset = (page - 1) * limit;
    const [videos] = await db.query(
        'SELECT * FROM douyin_videos WHERE platform = ? ORDER BY created_at DESC LIMIT ? OFFSET ?',
        [platform, parseInt(limit), parseInt(offset)]
    );
    const [totalResult] = await db.query(
        'SELECT COUNT(*) as total FROM douyin_videos WHERE platform = ?',
        [platform]
    );

    return {
        list: videos,
        total: totalResult[0].total,
        page: parseInt(page),
        limit: parseInt(limit)
    };
}
// 定义通用的错误处理函数
const handleError = (res, error) => {
    console.error('Error:', error);
    res.status(500).json({ code: -1, message: '服务器内部错误' });
};
// ---------------------------------抖音-----------------------------------
// 添加平台验证中间件
const validatePlatform = (req, res, next) => {
    const validPlatforms = ['douyin', 'xiaohongshu', 'kuaishouhao', 'weibo', 'toutiaohao'];
    if (!validPlatforms.includes(req.params.platform)) {
        return res.status(400).json({ code: -1, message: '无效的平台参数' });
    }
    next();
};

// 统一的视频列表接口
router.get('/:platform/videos', validatePlatform, async (req, res) => {
    try {
        const data = await getVideosByPlatform(req.params.platform, req.query.page, req.query.limit);
        res.json({ code: 0, data });
    } catch (error) {
        handleError(res, error);
    }
});

// 统一的视频详情接口
router.get('/:platform/video/:id', validatePlatform, async (req, res) => {
    try {
        const [video] = await db.query(
            'SELECT * FROM douyin_videos WHERE id = ? AND platform = ?',
            [req.params.id, req.params.platform]
        );

        if (!video[0]) {
            return res.status(404).json({ code: -1, message: '视频不存在' });
        }

        res.json({ code: 0, data: video[0] });
    } catch (error) {
        handleError(res, error);
    }
});

// 统一的删除视频接口
router.delete('/:platform/videos/:id', validatePlatform, async (req, res) => {
    try {
        await db.query(
            'DELETE FROM douyin_videos WHERE id = ? AND platform = ?',
            [req.params.id, req.params.platform]
        );
        res.json({ code: 0, message: '删除成功' });
    } catch (error) {
        handleError(res, error);
    }
});

// ---------------------------------other----------------------------------
// 获取七牛云上传凭证
router.get('/qiniu/uploadToken', async (req, res) => {
    const { key } = req.query;
    const uploadToken = generateUploadToken(key);
    res.json({ code: 0, data: uploadToken });
});

module.exports = router;
